<?php
if ( ! defined('ROOT')) exit('No direct script access allowed');

/**
 * 数据库工厂类
 * @author gzute
 * @link http://www.gzute.com
 */


class Db_factory
{
	public function get_db_object($params,$active_record_override = NULL)
	{
		if (is_string($params) AND strpos($params, '://') === FALSE)
		{
			$db = Base::load_config('database');
			if ( ! isset($db) OR count($db) == 0)
			{
				show_error('No database connection settings were found in the database config file.');
			}
			$active_group = Base::load_config('system','active_group');
			if ($params != '')
			{
				$active_group = $params;
			}
			if ( ! isset($active_group) OR ! isset($db[$active_group]))
			{
				show_error('You have specified an invalid database connection group.');
			}
			$params = $db[$active_group];
			
		}
		
		elseif (is_string($params))
		{
			if (($dns = @parse_url($params)) === FALSE)
			{
				show_error('Invalid DB Connection String');
			}
			$params = array(
							'dbdriver'	=> $dns['scheme'],
							'hostname'	=> (isset($dns['host'])) ? rawurldecode($dns['host']) : '',
							'username'	=> (isset($dns['user'])) ? rawurldecode($dns['user']) : '',
							'password'	=> (isset($dns['pass'])) ? rawurldecode($dns['pass']) : '',
							'database'	=> (isset($dns['path'])) ? rawurldecode(substr($dns['path'], 1)) : ''
						);
			// were additional config items set?
			if (isset($dns['query']))
			{
				parse_str($dns['query'], $extra);
	
				foreach ($extra as $key => $val)
				{
					// booleans please
					if (strtoupper($val) == "TRUE")
					{
						$val = TRUE;
					}
					elseif (strtoupper($val) == "FALSE")
					{
						$val = FALSE;
					}
	
					$params[$key] = $val;
				}
			}
		}
		// No DB specified yet?  Beat them senseless...
		if ( ! isset($params['dbdriver']) OR $params['dbdriver'] == '')
		{
			show_error('You have not selected a database type to connect to.');
		}
		$active_record = Base::load_config('system','active_record');
		
		if ($active_record_override !== NULL)
		{
			$active_record = $active_record_override;
		}
		Base::load_db_class('db_driver');
		
		if ( ! isset($active_record) OR $active_record == TRUE)
		{
			Base::load_db_class('db_active');
			
			if ( ! class_exists('DB'))
			{
				eval('class DB extends Db_active { }');
			}
		}
		else
		{
			if ( ! class_exists('DB'))
			{
				eval('class DB extends Db_driver { }');
			}
		}
		Base::load_db_class($params['dbdriver'].'_driver', $params['dbdriver']);
		$driver = ucfirst($params['dbdriver'].'_driver');
		$DB = new $driver($params);
		if ($DB->autoinit == TRUE)
		{
			$DB->initialize();
		}
		if (isset($params['stricton']) && $params['stricton'] == TRUE)
		{
			$DB->query('SET SESSION sql_mode="STRICT_ALL_TABLES"');
		}
		return $DB;
	}
}

//end of this file